﻿using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.RegularExpressions;
using housingsafety.server.Helpers;
using Microsoft.AspNetCore.WebUtilities;
using Newtonsoft.Json;

namespace housingsafety.server.Security
{
    /// <summary>
    /// 接口认证
    /// </summary>
    public class WebAPISign
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        [Required]
        public string UserId { get; set; }
        /// <summary>
        /// 时间戳
        /// </summary>
        [Required]
        public long Timestamp { get; set; }

        /// <summary>
        /// 随机数
        /// </summary>
        [Required]
        public string NonceStr { get; set; }

        /// <summary>
        /// JWT 哈希
        /// </summary>
        [Required]
        public string JwtHash { get; set; }

        /// <summary>
        /// 签名
        /// </summary>
        [Required]
        public string Sign { get; set; }

        /// <summary>
        /// 转为MAC
        /// </summary>
        /// <returns></returns>
        public string ToMsgAuthCode()
        {
            var originString = $"id={UserId}&ts={Timestamp}&nonce={NonceStr}&hash={JwtHash}&sign={Sign}";
            return UrlBase64.Encode(Encoding.UTF8.GetBytes(originString), PaddingPolicy.Discard);
        }

        /// <summary>
        /// 从MAC转换
        /// </summary>
        /// <param name="mac"></param>
        /// <returns></returns>
        public bool FromMsgAuthCode(string mac)
        {
            var originString = Encoding.UTF8.GetString(UrlBase64.Decode(mac));
            long ts = 0;
            var keyValuePairs = QueryHelpers.ParseNullableQuery(originString);
            if (!keyValuePairs.ContainsKey("id")
                || !keyValuePairs.ContainsKey("ts")
                || !keyValuePairs.ContainsKey("hash")
                || !keyValuePairs.ContainsKey("nonce")
                || !keyValuePairs.ContainsKey("sign")
                || !long.TryParse(keyValuePairs["ts"], out ts))
            {
                return false;
            }

            UserId = keyValuePairs["id"];
            Timestamp = ts;
            NonceStr = keyValuePairs["nonce"];
            Sign = keyValuePairs["sign"];
            JwtHash = keyValuePairs["hash"];

            return true;
        }
    }
}
